"""Bag转换窗口模块
实现Bag文件转换的进度显示窗口
"""

from PySide2.QtWidgets import (
    QDialog, QVBoxLayout, QLabel, QPushButton, QWidget, QShortcut
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QMovie, QFont, QKeySequence
from pathlib import Path
from gglobal import logger
from mooetoolapp.handlercore.language_manager import LanguageManager


class BagChangeWindow(QDialog):
    """Bag转换进度窗口类"""
    
    # 定义信号
    cancel_requested = Signal()  # 取消请求信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_window = parent
        self.setObjectName("bag_change_window")
        self.language_manager = LanguageManager()
        self.init_ui()
        self.setup_connections()
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle(self.language_manager.get_text("bag_convert_window_title", category="constants"))
        self.setFixedSize(400, 400)
        self.setWindowModality(Qt.ApplicationModal)
        
        # 设置窗口标志，隐藏关闭按钮但保持窗口可交互
        self.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint)
        
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 创建动画标签
        self.animation_label = QLabel()
        self.animation_label.setObjectName("bag_animation_label")
        self.animation_label.setAlignment(Qt.AlignCenter)
        self.animation_label.setMinimumHeight(120)
        
        # 加载动画
        self.setup_animation()
        
        # 创建进度文本标签
        self.progress_label = QLabel(self.language_manager.get_text("bag_convert_preparing", category="constants"))
        self.progress_label.setObjectName("bag_progress_label")
        self.progress_label.setAlignment(Qt.AlignCenter)
        self.progress_label.setWordWrap(True)
        
        # 创建取消按钮
        self.cancel_button = QPushButton(self.language_manager.get_text("bag_convert_cancel", category="constants"))
        self.cancel_button.setObjectName("bag_cancel_button")
        self.cancel_button.setFixedSize(100, 35)
        # 确保按钮可见
        self.cancel_button.setVisible(True)
        self.cancel_button.show()
        
        # 创建按钮容器并居中
        button_widget = QWidget()
        button_layout = QVBoxLayout(button_widget)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.addWidget(self.cancel_button, alignment=Qt.AlignCenter)
        
        # 添加到主布局
        main_layout.addWidget(self.animation_label)
        main_layout.addWidget(self.progress_label)
        main_layout.addStretch()
        main_layout.addWidget(button_widget)
        
    def setup_animation(self):
        """设置动画"""
        try:
            # 首先尝试加载GIF动画文件
            gif_path = ":/icon/bag2dbprogress.gif"
            
            # 尝试加载Qt资源中的GIF文件
            self.movie = QMovie(gif_path)
            if self.movie.isValid():
                self.animation_label.setMovie(self.movie)
                self.movie.start()
                logger.debug("GIF动画加载成功")
            else:
                # 如果GIF加载失败，使用文本动画作为后备
                self.animation_label.setText("🔄")
                self.animation_label.setObjectName("bag_animation_fallback")
                logger.debug("使用文本动画作为后备")
                
        except Exception as e:
            logger.error(f"加载动画失败: {e}")
            self.animation_label.setText(self.language_manager.get_text("bag_convert_processing", category="constants"))
            
    def setup_connections(self):
        """设置信号连接"""
        self.cancel_button.clicked.connect(self.on_cancel_clicked)
        logger.info("已连接取消按钮的clicked信号")
        
        # 添加键盘快捷键作为备用方案
        self.escape_shortcut = QShortcut(QKeySequence(Qt.Key_Escape), self)
        self.escape_shortcut.activated.connect(self.on_cancel_clicked)
        logger.info("已设置ESC键快捷键")
        
        # 设置按钮为默认按钮并获得焦点
        self.cancel_button.setDefault(True)
        self.cancel_button.setFocus()
        
        # 添加鼠标事件处理用于调试
        self.cancel_button.mousePressEvent = self.debug_mouse_press
        
    def debug_mouse_press(self, event):
        """调试鼠标按下事件"""
        logger.info("检测到鼠标按下事件")
        print("DEBUG: 鼠标按下事件")
        logger.info(f"事件类型: {event.type()}, 按钮: {event.button()}")
        
        # 强制触发点击事件进行测试
        if event.button() == Qt.LeftButton:
            logger.info("强制触发按钮点击")
            self.cancel_button.click()
        
        # 调用原始的鼠标按下事件
        QPushButton.mousePressEvent(self.cancel_button, event)
        
    def on_cancel_clicked(self):
        """取消按钮点击事件"""
        logger.info("取消按钮被点击")
        print("DEBUG: 取消按钮被点击")
        logger.info(f"按钮启用状态: {self.cancel_button.isEnabled()}")
        logger.info(f"窗口启用状态: {self.isEnabled()}")
        logger.info(f"按钮可见状态: {self.cancel_button.isVisible()}")
        logger.info(f"窗口可见状态: {self.isVisible()}")
        
        # 强制处理点击事件
        try:
            self.cancel_requested.emit()
            logger.info("成功发射cancel_requested信号")
        except Exception as e:
            logger.error(f"发射信号时出错: {e}")
            # 如果信号发射失败，直接关闭窗口
            self.close()
        
    def update_progress(self, message):
        """更新进度信息"""
        self.progress_label.setText(message)
        logger.debug(f"进度更新: {message}")
        
    def conversion_finished(self, success, message):
        """转换完成处理"""
        logger.info(f"conversion_finished被调用: 成功={success}")
        print(f"DEBUG: conversion_finished被调用: 成功={success}")
        
        # 停止动画
        if hasattr(self, 'movie'):
            self.movie.stop()
            
        # 更新界面
        if success:
            self.animation_label.setText("✓")
            self.animation_label.setObjectName("bag_animation_success")
            self.progress_label.setText(self.language_manager.get_text("bag_convert_success", category="constants"))
        else:
            self.animation_label.setText("✗")
            self.animation_label.setObjectName("bag_animation_error")
            self.progress_label.setText(self.language_manager.get_text("bag_convert_failed", category="constants"))
            
        # 更改按钮为关闭
        self.cancel_button.setText(self.language_manager.get_text("bag_convert_close", category="constants"))
        logger.info(f"按钮文本已更改为: {self.cancel_button.text()}")
        
        # 确保按钮被启用
        self.cancel_button.setEnabled(True)
        logger.info("已明确启用按钮")
        
        # 检查按钮状态
        logger.info(f"转换完成后按钮启用状态: {self.cancel_button.isEnabled()}")
        logger.info(f"转换完成后按钮可见状态: {self.cancel_button.isVisible()}")
        logger.info(f"窗口启用状态: {self.isEnabled()}")
        
        # 断开所有现有连接
        try:
            self.cancel_button.clicked.disconnect()
            logger.info("已断开按钮的现有连接")
        except TypeError:
            # 如果没有连接的信号，disconnect会抛出TypeError，这是正常的
            logger.info("按钮没有现有连接需要断开")
            pass
        
        # 连接关闭功能
        self.cancel_button.clicked.connect(self.close)
        logger.info("已连接按钮到关闭功能")
        
        # 强制刷新按钮状态
        self.cancel_button.update()
        self.cancel_button.repaint()
        logger.info("已刷新按钮显示状态")
        
        logger.info(f"转换完成: 成功={success}, 消息={message}")
        
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 由于我们没有禁用父窗口，所以不需要重新启用
        # if self.parent_window:
        #     self.parent_window.setEnabled(True)
        
        logger.info("窗口正在关闭")
            
        # 停止动画
        if hasattr(self, 'movie'):
            self.movie.stop()
            
        super().closeEvent(event)
        
    def show(self):
        """显示窗口"""
        # 不禁用父窗口，使用模态性来阻止交互
        # if self.parent_window:
        #     self.parent_window.setEnabled(False)
        
        # 确保当前窗口和按钮都是启用状态
        self.setEnabled(True)
        self.cancel_button.setEnabled(True)
        self.cancel_button.setVisible(True)
        self.cancel_button.show()
        logger.info(f"显示窗口时 - 窗口启用状态: {self.isEnabled()}, 按钮启用状态: {self.cancel_button.isEnabled()}, 按钮可见状态: {self.cancel_button.isVisible()}")
            
        super().show()